<script lang="ts" setup>
import { onUnmounted, reactive, ref, toRefs, unref, watchEffect } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { info, edit, add } from "@/api/hnvmns-device-center/device";
import { filterOptionDict } from "@/utils/filters";
import { useDict } from "@/hooks/useDict";
interface Props {
  id?: IDType;
  type: DialogType;
}
const props = withDefaults(defineProps<Props>(), {});
const emits = defineEmits(["getList", "update:modelValue"]);
const { type } = toRefs(props);
const { getDictList } = useDict();
const dictObj = getDictList(["systemid"]);

const initForm: DeviceListFace = {
  productId: "",
  name: "",
};

const ruleFormRef = ref<FormInstance>();
const ruleForm = ref<DeviceListFace>();
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
});
const loading = ref<boolean>(false);

const getInfo = () => {
  loading.value = true;
  if (!props.id) return;
  info(props.id)
    .then((res) => {
      ruleForm.value = res.data;
    })
    .finally(() => {
      loading.value = false;
    });
};

const watchId = watchEffect(() => {
  if (type.value !== "create") {
    getInfo();
  } else {
    ruleForm.value = Object.assign({}, initForm);
  }
});
onUnmounted(() => {
  watchId();
});
const subLoading = ref(false);
const submitForm = async () => {
  if (type.value === "view") return handleClose();
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (!valid) return;
    subLoading.value = true;
    if (type.value === "create") {
      add(ruleForm.value!)
        .then((res) => {
          ElMessage.success("添加成功");
          emits("getList");
          handleClose();
        })
        .catch(() => {
          subLoading.value = false;
        });
    } else if (type.value === "edit") {
      edit(ruleForm.value!)
        .then((res) => {
          ElMessage.success("修改成功");
          emits("getList");
          handleClose();
        })
        .catch(() => {
          subLoading.value = false;
        });
    }
  });
};
const handleClose = () => {
  emits("update:modelValue");
};
defineExpose({
  submitForm,
});
</script>

<template>
  <el-form
    ref="ruleFormRef"
    inline
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="ruleForm"
    :close-on-click-modal="type === 'view'"
    :disabled="type === 'view'"
    :class="type === 'view' ? 'viewForm' : ''"
    v-loading="loading"
  >
    <el-form-item label="名称" prop="name">
      <el-input v-model="ruleForm.name" />
    </el-form-item>
  </el-form>
  <div class="dialog-form-footer">
    <el-button @click="handleClose">关闭</el-button>
    <el-button type="primary" v-if="type !== 'view'" @click="submitForm">确定</el-button>
  </div>
</template>
